<template>
  <div>
    <el-card style="margin-bottom: 20px">
      <el-form :inline="true" class="form-top">
        <el-form-item label="用户名：">
          <el-input style="width: 120px" v-model="searchData"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="search"
            :disabled="searchData ? false : true"
          >
            搜索
          </el-button>
          <el-button type="primary" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <el-button type="primary" @click="addUser">添加</el-button>
      <!--  -->
      <el-popconfirm title="确定删除吗" @confirm="batchDelete">
        <template #reference>
          <el-button
            type="danger"
            :disabled="selectedId.length > 0 ? false : true"
          >
            批量删除
          </el-button>
        </template>
      </el-popconfirm>
      <el-table
        border
        style="margin-top: 20px"
        :data="userArray"
        @selection-change="selectionChange"
      >
        <el-table-column type="selection"></el-table-column>
        <el-table-column label="#" width="50px" type="index"></el-table-column>
        <el-table-column label="ID" width="70px" prop="id"></el-table-column>
        <el-table-column label="用户账号" prop="username"></el-table-column>
        <el-table-column label="用户名称" prop="name"></el-table-column>
        <el-table-column
          label="用户角色"
          prop="roleName"
          width="100px"
        ></el-table-column>
        <el-table-column label="创建时间" prop="createTime"></el-table-column>
        <el-table-column label="更新时间" prop="updateTime"></el-table-column>
        <el-table-column label="操作" width="200px">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="role(row)">
              分配角色
            </el-button>
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="editUser(row)"
            ></el-button>
            <el-popconfirm title="确认删除吗" @confirm="deleteInfo(row)">
              <template #reference>
                <el-button
                  type="primary"
                  size="small"
                  icon="Delete"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 20px"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[3, 5, 7, 9]"
        :disabled="false"
        :background="true"
        layout=" prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @current-change="getAllUser"
        @size-change="getAllUser()"
      />
    </el-card>
    <!-- 抽屉组1 -->
    <el-drawer
      v-model="drawer"
      style="border-radius: 24px; width: 280px"
      :close-on-click-modal="false"
      :with-header="true"
      :show-close="false"
    >
      <template #header>
        <h4 class="unselectable">{{ flag2 ? title : title2 }}</h4>
        <el-icon
          style="
            color: #000;
            font-size: 25px;
            filter: drop-shadow(0 0 3px #000);
          "
          @click="cancel"
        >
          <Close />
        </el-icon>
      </template>
      <template #default>
        <!-- 抽屉的表单内容 -->
        <el-form :model="userObj" :rules="rules" ref="formValue">
          <el-form-item label="用户名称：" prop="name">
            <el-input
              placeholder="请输入用户名称"
              v-model="userObj.name"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户账号：" prop="username">
            <el-input
              placeholder="请输入用户账号"
              v-model="userObj.username"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户密码：" prop="password" v-if="flag">
            <el-input
              placeholder="请输入用户密码"
              v-model="userObj.password"
            ></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="confirmClick()">确认</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 抽屉组2 -->
    <el-drawer
      v-model="drawer2"
      style="border-radius: 24px; width: 280px"
      :close-on-click-modal="false"
      :with-header="true"
      :show-close="false"
    >
      <template #header>
        <h4 class="unselectable">分配角色</h4>
        <el-icon
          style="
            color: #000;
            font-size: 25px;
            filter: drop-shadow(0 0 3px #000);
          "
          @click="cancelDrawer2"
        >
          <Close />
        </el-icon>
      </template>
      <template #default>
        <!-- 抽屉的表单内容 -->
        <el-form>
          <el-form-item label="用户姓名">
            <el-input
              placeholder="请输入用户姓名"
              disabled
              v-model="input"
            ></el-input>
          </el-form-item>
          <el-form-item label="是否全选">
            <el-checkbox
              v-model="checkAll"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
            >
              全选
            </el-checkbox>
          </el-form-item>
          <el-form-item label="角色展示">
            <el-checkbox-group
              v-model="checkedRoles"
              @change="handleCheckedRolesChange(checkedRoles)"
            >
              <el-checkbox
                v-for="(item, index) in roles"
                :key="index"
                :label="item"
                :value="item"
              >
                {{ item.roleName }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelDrawer2">取消</el-button>
          <el-button type="primary" @click="confirmDrawer2()">确认</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import isUpDate from '../../../store/modules/update'
import { ref, onMounted, nextTick, watch } from 'vue'
import {
  reqGetUserInfo,
  reqAddOrUpdata,
  reqDelete,
  reqGetRoles,
  reqSaveRoles,
  reqSelectDelete,
} from '../../../api/acl/user'
import type {
  ApiResponse,
  userRecordObj,
  UserRecord,
} from '../../../api/acl/user/userType'
import { ElMessage } from 'element-plus'
import type {
  Response,
  allRolesList,
  assignRoles,
} from '../../../api/acl/user/rolesType'
import { assignUserRole } from '../../../api/acl/user/assignUser'
//抽屉标题
let title = ref('添加用户')
let title2 = ref('编辑用户')
//页码总数
let total = ref(30)
//当前页数
let currentPage = ref(1)
//用户表格数据
let userArray = ref<userRecordObj>([])
//每页数量
let pageSize = ref(5)
//抽屉控制变量
const drawer = ref(false)
//获取抽屉表单实例
let formValue = ref<any>('')
//用于抽屉密码的显示和隐藏
let flag = ref<boolean>(true)
//定义抽屉组2的显示和隐藏
let drawer2 = ref<boolean>(false)
//用于控制抽屉1编辑用户和添加用户的切换
let flag2 = ref<boolean>(true)
//定义多选框全部角色数据
let roles = ref<allRolesList>([])
//定义复选框全选变量
let checkAll = ref<boolean>(false)
//用于控制全选框初始状态
const isIndeterminate = ref(true)
//定义已经选中的角色
let checkedRoles = ref<assignRoles>([])
//定义抽屉2输入框绑定值
const input = ref('')
//用于收集多选框所选择的数据id
let selectedId = ref<number[]>([])
//用于判断添加/编辑是否刷新页面，添加不用刷新，编辑用户账号需要刷新页面
let flag3 = ref<boolean>(false)
//定义搜索框数据
let searchData = ref<string>('')
//用于调用仓库的刷新业务
const updataData = isUpDate()
//定义抽屉组内的表单信息（收集抽屉信息）
let userObj = ref<UserRecord>({
  id: '',
  name: '',
  username: '',
  password: '',
})
//定义数据，用户收集用户选择的角色id和哪个用户,点击提交，将data携带给请求接口
let drawer2Data = ref<assignUserRole>({
  roleIdList: checkedRoles.value.map((item) => {
    return item.id as number
  }),
  userId: userObj.value.id as number,
})
//组件挂载
onMounted(() => {
  //调用接口函数
  getAllUser()
})
//定义调用接口
async function getAllUser(page = 1) {
  //当前页数
  currentPage.value = page
  //掉用接口
  let result: ApiResponse = await reqGetUserInfo(
    currentPage.value,
    pageSize.value,
    searchData.value,
  )
  /*  console.log(result) */
  //赋值（分页）
  pageSize.value = result.data.size
  //赋值（总页数）
  total.value = result.data.total
  //赋值（用户数据）
  userArray.value = result.data.records
}
//添加用户回调
function addUser() {
  //添加用户flag3变化
  flag3.value = true
  //title切换
  flag2.value = true
  //抽屉内的密码框显示
  flag.value = true
  //抽屉打开
  drawer.value = true
  //清空数据
  userObj.value.id = ''
  userObj.value.username = ''
  userObj.value.name = ''
  userObj.value.password = ''

  //清空表单验证信息
  nextTick(() => {
    formValue.value.clearValidate('username')
    formValue.value.clearValidate('name')
    formValue.value.clearValidate('password')
  })
}
//取消按钮回调
function cancel() {
  //调用接口函数(目的是重新渲染数据)
  getAllUser(currentPage.value)
  //抽屉关闭
  drawer.value = false
}
//确认(保存drawer1)函数回调
async function confirmClick() {
  /*  console.log(111111111111111) */
  //表单校验通过后再发请求
  //调用接口
  /*   await formValue.value.validate() */
  let result: any = await reqAddOrUpdata(userObj.value)
  ElMessage({
    type: 'success',
    message: '添加成功',
  })
  //刷新数据
  getAllUser(userObj.value.id ? currentPage.value : 1)
  //刷新页面
  /* console.log(localStorage.getItem('username')) */
  if (!flag3.value) {
    window.location.reload()
  }
  //延时抽屉关闭
  setTimeout(() => {
    drawer.value = false
  }, 200)
}
//编辑回调
function editUser(row: UserRecord) {
  //flag3切换
  flag3.value = false
  //标题切换
  flag2.value = false
  //隐藏密码
  flag.value = false
  //打开抽屉
  drawer.value = true
  /*   console.log(row); */
  //收集所点击那一行的用户信息，保存于userObj
  userObj.value = row

  //清空表单验证信息
  nextTick(() => {
    formValue.value.clearValidate('username')
    formValue.value.clearValidate('name')
    formValue.value.clearValidate('password')
  })
}
//删除回调
async function deleteInfo(row: UserRecord) {
  //调用删除接口
  let result = await reqDelete(row.id as number)
  /*  console.log(result) */
  //判断接口条件
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    //重新渲染数据
    getAllUser(currentPage.value > 1 ? currentPage.value : 1)
  } else {
    ElMessage({
      type: 'error',
      message: '操作失败',
    })
  }
}
//定义用户名校验函数
function validatorUsername(rules: any, value: any, callback: any) {
  if (value.trim().length > 5) {
    callback()
  } else {
    callback(new Error('用户名长度需大于5位'))
  }
}
//定义密码校验函数
function validatorPassword(rules: any, value: any, callback: any) {
  if (value.length > 5) {
    callback()
  } else {
    callback(new Error('密码长度需大于5位'))
  }
}
//定义密码校验函数
function validatorName(rules: any, value: any, callback: any) {}

//定义抽屉表单校验规则
const rules = {
  username: [{ required: true, trigger: 'blur', validator: validatorUsername }],
  password: [{ required: true, trigger: 'blur', validator: validatorPassword }],
  name: [{ required: true, trigger: 'blur', validator: validatorName }],
}

//定义抽屉2的取消回调
function cancelDrawer2() {
  //关闭抽屉
  drawer2.value = false
}
//定义分配角色回调
async function role(row: UserRecord) {
  //收集所点击那一行的用户信息，保存于userObj
  userObj.value = row

  //打开抽屉2
  drawer2.value = true
  //传递用户名称
  input.value = row.name as string
  /* console.log(row.id); */
  //发送角色请求
  let result: Response = await reqGetRoles(row.id as number | string)

  //判断
  if (result.code == 200) {
    /* console.log(result); */
    //赋值(已经选中的角色和全部角色)
    checkedRoles.value = result.data.assignRoles
    roles.value = result.data.allRolesList
    /*  console.log(roles.value) */
    //赋值
    drawer2Data.value.userId = row.id as number
    drawer2Data.value.roleIdList = checkedRoles.value.map((item) => {
      return item.id as number
    })
    //监测用户的角色选择点击行为
    watch(
      () => checkedRoles.value,
      () => {
        /*   drawer2Data.value.userId = row.id as number */
        drawer2Data.value.roleIdList = checkedRoles.value.map((item) => {
          return item.id as number
        })
      },
    )
  } else {
    ElMessage({
      type: 'error',
      message: '请求失败',
    })
  }
}
//定义抽屉组2的确认函数
async function confirmDrawer2() {
  //发送请求
  let result: any = await reqSaveRoles(drawer2Data.value)

  //判断
  if (result.code == 200) {
    /*  console.log(result) */
    ElMessage({
      type: 'success',
      message: '添加成功',
    })
    getAllUser(currentPage.value)
  } else {
    ElMessage({
      type: 'error',
      message: '操作失败',
    })
  }

  //关闭抽屉
  drawer2.value = false
}
//定义全选回调
const handleCheckAllChange = (val: boolean) => {
  checkedRoles.value = val ? roles.value : []
  isIndeterminate.value = false
}
//定义单个角色点击回调
const handleCheckedRolesChange = (value: allRolesList) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === roles.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < roles.value.length
}

//当选择多选框时触发的回调
function selectionChange(val: any) {
  /* console.log(value); */
  //用于接受val每一项里面的id
  selectedId.value = val.map((item: UserRecord) => {
    return item.id
  })
  /* console.log(selectedId.value); */
}
//批量删除回调
async function batchDelete() {
  //调用批量删除接口
  let result = await reqSelectDelete(selectedId.value)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getAllUser(currentPage.value)
  } else {
    ElMessage({
      type: 'error',
      message: '操作失败',
    })
  }
}
//定义搜索回调哦
function search() {
  //调用函数
  getAllUser()
  //搜索框清空
  searchData.value = ''
}
//定义重置回调
function reset() {
  updataData.update = !updataData.update
}
</script>

<style scoped lang="scss">
.form-top {
  display: flex;
  justify-content: space-between;
}
.el-drawer__header .el-drawer__close {
  display: none; /* 隐藏关闭按钮 */
}
</style>
